let contentMatchUrls = []

chrome.runtime.onMessage.addListener(async ({ action, preload }, sender, sendResponse) => {
  if (action == 'setBookList') {
    try {
      await chrome.storage.local.set({ 'chrome-novel-plugin_bookList': preload })
      const tabs = await chrome.tabs.query({})
      await getMatchUrls()
      for (let { url, id } of tabs) {
        if (!isMatch(url)) continue
        chrome.tabs.sendMessage(id, {
          action: 'notifyContentUpdate',
          preload,
        })
      }
    } catch (err) {
      console.log('try catch err', err)
    } finally {
      sendResponse('')
    }
  }
  return true
})

/**获取所有可以匹配的url */
async function getMatchUrls() {
  if (contentMatchUrls.length) return
  let manifest = await chrome.runtime.getManifest()
  let { content_scripts } = manifest
  contentMatchUrls = content_scripts.reduce((arr, { matches }) => (arr.push(...matches), arr), []).map((url) => url.replace(/\*:\/\/(.*)\/\*/, '$1'))
}

/**判断是否匹配对插件生效的网址 */
function isMatch(url) {
  for (let u of contentMatchUrls) {
    if (url.includes(u)) return true
  }
  return false
}
